package com.authsphere.security.account.api.lock;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/22 21:00
 **/
public class InMemoryLockoutRepository implements LockoutRepository {
    private final static Map<String, LockedAccount> LOCKED_ACCOUNT_MAP = Maps.newConcurrentMap();

    @Override
    public void save(LockedAccount lockedAccount) {
        LOCKED_ACCOUNT_MAP.put(lockedAccount.getUsername(), lockedAccount);
    }

    @Override
    public void update(LockedAccount lockedAccount) {
        LOCKED_ACCOUNT_MAP.put(lockedAccount.getUsername(), lockedAccount);
    }

    @Override
    public LockedAccount findByUsername(String username) {
        return LOCKED_ACCOUNT_MAP.get(username);
    }

    @Override
    public void deleteByUsername(String username) {
        LOCKED_ACCOUNT_MAP.remove(username);
    }

    @Override
    public List<LockedAccount> getLockedAccounts(String username) {
        List<LockedAccount> lockedAccountList = Lists.newArrayList();
        for (Map.Entry<String, LockedAccount> entry : LOCKED_ACCOUNT_MAP.entrySet()) {
            if (StringUtils.containsAny(entry.getKey(), username)) {
                lockedAccountList.add(entry.getValue());
            }
        }
        return lockedAccountList;
    }

    @Override
    public List<String> findAllLockedAccounts() {
        return Lists.newArrayList(LOCKED_ACCOUNT_MAP.keySet());
    }
}
